<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>德州扑克</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Courier New', monospace;
            background: #1a1a1a;
            color: #fff;
            padding: 20px;
            line-height: 1.4;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        /* 状态栏 */
        .status-bar {
            background: #333;
            padding: 10px;
            margin-bottom: 20px;
            border-radius: 5px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .connection-status {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .status-dot {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: #ff4444;
        }

        .status-dot.connected {
            background: #44ff44;
        }

        /* 房间设置 */
        .setup-container {
            background: #333;
            padding: 30px;
            border-radius: 5px;
            max-width: 500px;
            margin: 50px auto;
        }

        .setup-title {
            text-align: center;
            font-size: 24px;
            margin-bottom: 30px;
            color: #ffd700;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 8px;
            border: 1px solid #555;
            background: #222;
            color: #fff;
            border-radius: 3px;
        }

        .btn {
            background: #007acc;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 3px;
            cursor: pointer;
            font-size: 14px;
        }

        .btn:hover {
            background: #005a99;
        }

        .btn:disabled {
            background: #666;
            cursor: not-allowed;
        }

        .btn-danger {
            background: #cc4125;
        }

        .btn-danger:hover {
            background: #a0341c;
        }

        .btn-success {
            background: #25cc4b;
        }

        .btn-success:hover {
            background: #1ca83a;
        }

        /* 游戏界面 */
        .game-container {
            display: none;
        }

        .game-layout {
            display: grid;
            grid-template-columns: 300px 1fr 300px;
            gap: 20px;
            min-height: 600px;
        }

        /* 左侧面板 */
        .left-panel {
            background: #333;
            padding: 20px;
            border-radius: 5px;
        }

        .game-info h3 {
            color: #ffd700;
            margin-bottom: 15px;
            border-bottom: 1px solid #555;
            padding-bottom: 5px;
        }

        .info-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            padding: 5px 0;
            border-bottom: 1px solid #444;
        }

        .info-value {
            font-weight: bold;
            color: #ffd700;
        }

        /* 中央游戏区 */
        .game-area {
            background: #333;
            padding: 20px;
            border-radius: 5px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: space-between;
        }

        /* 公共牌 */
        .community-section {
            text-align: center;
            margin-bottom: 30px;
        }

        .community-cards {
            display: flex;
            gap: 10px;
            justify-content: center;
            margin-top: 10px;
        }

        .card {
            width: 50px;
            height: 70px;
            background: #fff;
            color: #000;
            border: 1px solid #ccc;
            border-radius: 5px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: bold;
        }

        .card.empty {
            background: #555;
            color: #999;
        }

        .card.red {
            color: #d63031;
        }

        /* 手牌 */
        .your-hand-section {
            text-align: center;
            margin-top: 30px;
        }

        .your-hand {
            display: flex;
            gap: 10px;
            justify-content: center;
            margin-top: 10px;
        }

        .your-hand .card {
            width: 60px;
            height: 85px;
            font-size: 14px;
        }

        /* 操作面板 */
        .action-section {
            background: #444;
            padding: 20px;
            border-radius: 5px;
            margin-top: 20px;
            text-align: center;
            min-height: 150px;
            display: flex;
            flex-direction: column;
            justify-content: center;
        }

        .action-section.your-turn {
            background: #2d5016;
            border: 2px solid #44ff44;
        }

        .countdown {
            font-size: 24px;
            font-weight: bold;
            color: #ff4444;
            margin-bottom: 15px;
        }

        .action-buttons {
            display: flex;
            gap: 10px;
            justify-content: center;
            flex-wrap: wrap;
        }

        .action-btn {
            padding: 8px 16px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            font-size: 12px;
        }

        .bet-input-section {
            margin-top: 15px;
            display: none;
        }

        .bet-input {
            padding: 5px;
            width: 100px;
            margin: 0 10px;
            text-align: center;
            border: 1px solid #555;
            background: #222;
            color: #fff;
        }

        /* 右侧玩家列表 */
        .right-panel {
            background: #333;
            padding: 20px;
            border-radius: 5px;
        }

        .players-list {
            list-style: none;
        }

        .player-item {
            background: #444;
            margin-bottom: 10px;
            padding: 15px;
            border-radius: 3px;
            border-left: 3px solid #666;
        }

        .player-item.current-turn {
            border-left-color: #44ff44;
            background: #2d5016;
        }

        .player-item.folded {
            opacity: 0.5;
            border-left-color: #ff4444;
        }

        .player-name {
            font-weight: bold;
            margin-bottom: 5px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .ai-badge {
            background: #cc4125;
            color: white;
            font-size: 10px;
            padding: 2px 6px;
            border-radius: 3px;
        }

        .player-info {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 5px;
            font-size: 12px;
            color: #ccc;
        }

        .player-info span {
            display: flex;
            justify-content: space-between;
        }

        .chips {
            color: #ffd700;
        }

        .bet {
            color: #ff6b6b;
        }

        /* 消息日志 */
        .message-log {
            background: #222;
            padding: 10px;
            border-radius: 3px;
            height: 200px;
            overflow-y: auto;
            font-size: 12px;
            margin-top: 20px;
        }

        .log-message {
            margin-bottom: 5px;
            padding: 3px 0;
            border-bottom: 1px solid #333;
        }

        .log-time {
            color: #888;
            font-size: 10px;
        }

        /* 响应式 */
        @media (max-width: 768px) {
            .game-layout {
                grid-template-columns: 1fr;
                gap: 10px;
            }

            .left-panel, .right-panel {
                order: 1;
            }

            .game-area {
                order: 0;
            }
        }
    </style>
</head>
<body>
    <!-- 状态栏 -->
    <div class="status-bar">
        <div class="connection-status">
            <div class="status-dot" id="statusDot"></div>
            <span id="connectionText">连接中...</span>
        </div>
        <div id="roomInfo">正在检查房间状态...</div>
    </div>

    <div class="container">
        <!-- 房间设置界面 -->
        <div class="setup-container" id="setupContainer">
            <h2 class="setup-title">德州扑克</h2>

            <!-- 创建房间 -->
            <div id="createRoomForm" style="display: none;">
                <div class="form-group">
                    <label for="playerName">玩家昵称</label>
                    <input type="text" id="playerName" placeholder="请输入您的昵称" maxlength="20">
                </div>

                <div class="form-group">
                    <label for="totalPlayers">总玩家数</label>
                    <select id="totalPlayers">
                        <option value="2">2人桌</option>
                        <option value="3">3人桌</option>
                        <option value="4" selected>4人桌</option>
                        <option value="5">5人桌</option>
                        <option value="6">6人桌</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="aiPlayers">AI玩家数</label>
                    <select id="aiPlayers">
                        <option value="1">1个AI</option>
                        <option value="2">2个AI</option>
                        <option value="3" selected>3个AI</option>
                        <option value="4">4个AI</option>
                        <option value="5">5个AI</option>
                    </select>
                </div>

                <button class="btn" id="createRoomBtn">创建房间</button>
            </div>

            <!-- 加入房间 -->
            <div id="joinRoomForm" style="display: none;">
                <div class="form-group">
                    <label for="joinPlayerName">玩家昵称</label>
                    <input type="text" id="joinPlayerName" placeholder="请输入您的昵称" maxlength="20">
                </div>

                <div id="roomStatusInfo">
                    <h4>房间信息</h4>
                    <div class="info-item">
                        <span>玩家数量:</span>
                        <span id="currentPlayers">-/-</span>
                    </div>
                    <div class="info-item">
                        <span>AI数量:</span>
                        <span id="aiCount">-</span>
                    </div>
                    <div class="info-item">
                        <span>房间状态:</span>
                        <span id="roomStatus">-</span>
                    </div>
                </div>

                <button class="btn" id="joinRoomBtn">加入房间</button>
            </div>

            <!-- 等待房间 -->
            <div id="waitingRoom" style="display: none;">
                <h3>等待其他玩家...</h3>
                <p>房间已创建，等待玩家加入</p>
                <button class="btn btn-success" id="startGameBtn" style="display: none;">开始游戏</button>
            </div>
        </div>

        <!-- 游戏主界面 -->
        <div class="game-container" id="gameContainer">
            <div class="game-layout">
                <!-- 左侧游戏信息 -->
                <div class="left-panel">
                    <div class="game-info">
                        <h3>游戏信息</h3>
                        <div class="info-item">
                            <span>游戏状态:</span>
                            <span class="info-value" id="gameState">-</span>
                        </div>
                        <div class="info-item">
                            <span>当前轮次:</span>
                            <span class="info-value" id="currentRound">-</span>
                        </div>
                        <div class="info-item">
                            <span>底池:</span>
                            <span class="info-value" id="potAmount">$0</span>
                        </div>
                        <div class="info-item">
                            <span>当前下注:</span>
                            <span class="info-value" id="currentBet">$0</span>
                        </div>
                        <div class="info-item">
                            <span>需要跟注:</span>
                            <span class="info-value" id="toCall">$0</span>
                        </div>
                        <div class="info-item">
                            <span>最小加注:</span>
                            <span class="info-value" id="minRaise">$0</span>
                        </div>
                    </div>

                    <!-- 消息日志 -->
                    <div class="message-log" id="messageLog"></div>
                </div>

                <!-- 中央游戏区 -->
                <div class="game-area">
                    <!-- 公共牌 -->
                    <div class="community-section">
                        <h3>公共牌</h3>
                        <div class="community-cards" id="communityCards">
                            <div class="card empty">?</div>
                            <div class="card empty">?</div>
                            <div class="card empty">?</div>
                            <div class="card empty">?</div>
                            <div class="card empty">?</div>
                        </div>
                    </div>

                    <!-- 玩家手牌 -->
                    <div class="your-hand-section">
                        <h3>你的手牌</h3>
                        <div class="your-hand" id="yourHand">
                            <div class="card empty">?</div>
                            <div class="card empty">?</div>
                        </div>
                    </div>

                    <!-- 操作面板 -->
                    <div class="action-section" id="actionSection">
                        <div id="waitingMessage">
                            <p>等待其他玩家行动...</p>
                        </div>

                        <div id="yourTurnSection" style="display: none;">
                            <div class="countdown" id="countdown"></div>

                            <div class="action-buttons" id="actionButtons">
                                <!-- 动态生成按钮 -->
                            </div>

                            <div class="bet-input-section" id="betInputSection">
                                <label>下注金额:</label>
                                <input type="number" class="bet-input" id="betAmountInput" min="1" step="1">
                                <button class="btn btn-success" id="betConfirm">确认</button>
                                <button class="btn btn-danger" id="betCancel">取消</button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 右侧玩家列表 -->
                <div class="right-panel">
                    <h3>玩家列表</h3>
                    <ul class="players-list" id="playersList">
                        <!-- 动态生成玩家 -->
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <script>
        class PokerGame {
            constructor() {
                this.ws = null;
                this.gameState = null;
                this.playerName = '';
                this.currentBetAction = null;
                this.countdownTimer = null;
                this.countdownSeconds = 0;

                this.initializeElements();
                this.bindEvents();
                this.checkRoomStatus();
                this.connectWebSocket();
            }

            initializeElements() {
                this.elements = {
                    // 状态相关
                    statusDot: document.getElementById('statusDot'),
                    connectionText: document.getElementById('connectionText'),
                    roomInfo: document.getElementById('roomInfo'),

                    // 界面容器
                    setupContainer: document.getElementById('setupContainer'),
                    createRoomForm: document.getElementById('createRoomForm'),
                    joinRoomForm: document.getElementById('joinRoomForm'),
                    waitingRoom: document.getElementById('waitingRoom'),
                    gameContainer: document.getElementById('gameContainer'),

                    // 房间设置
                    playerName: document.getElementById('playerName'),
                    totalPlayers: document.getElementById('totalPlayers'),
                    aiPlayers: document.getElementById('aiPlayers'),
                    createRoomBtn: document.getElementById('createRoomBtn'),
                    joinPlayerName: document.getElementById('joinPlayerName'),
                    joinRoomBtn: document.getElementById('joinRoomBtn'),
                    startGameBtn: document.getElementById('startGameBtn'),

                    // 游戏信息
                    gameState: document.getElementById('gameState'),
                    currentRound: document.getElementById('currentRound'),
                    potAmount: document.getElementById('potAmount'),
                    currentBet: document.getElementById('currentBet'),
                    toCall: document.getElementById('toCall'),
                    minRaise: document.getElementById('minRaise'),

                    // 游戏区域
                    communityCards: document.getElementById('communityCards'),
                    yourHand: document.getElementById('yourHand'),
                    playersList: document.getElementById('playersList'),

                    // 操作相关
                    actionSection: document.getElementById('actionSection'),
                    waitingMessage: document.getElementById('waitingMessage'),
                    yourTurnSection: document.getElementById('yourTurnSection'),
                    countdown: document.getElementById('countdown'),
                    actionButtons: document.getElementById('actionButtons'),
                    betInputSection: document.getElementById('betInputSection'),
                    betAmountInput: document.getElementById('betAmountInput'),
                    betConfirm: document.getElementById('betConfirm'),
                    betCancel: document.getElementById('betCancel'),

                    // 消息日志
                    messageLog: document.getElementById('messageLog')
                };
            }

            bindEvents() {
                // 房间事件
                this.elements.createRoomBtn.addEventListener('click', () => this.createRoom());
                this.elements.joinRoomBtn.addEventListener('click', () => this.joinRoom());
                this.elements.startGameBtn.addEventListener('click', () => this.startGame());
                this.elements.totalPlayers.addEventListener('change', () => this.updateAiOptions());

                // 下注事件
                this.elements.betConfirm.addEventListener('click', () => this.confirmBet());
                this.elements.betCancel.addEventListener('click', () => this.cancelBet());
                this.elements.betAmountInput.addEventListener('keypress', (e) => {
                    if (e.key === 'Enter') this.confirmBet();
                });
            }

            async checkRoomStatus() {
                try {
                    const response = await fetch('/api/room/status');
                    const data = await response.json();

                    if (data.success) {
                        this.updateRoomUI(data.data);
                    } else {
                        this.log('检查房间状态失败');
                    }
                } catch (error) {
                    this.log('无法连接到服务器');
                    this.elements.roomInfo.textContent = '服务器连接失败';
                }
            }

            updateRoomUI(roomData) {
                const { room_state, players_count, total_players, ai_players } = roomData;

                if (room_state === 'waiting_for_players' && players_count === 0) {
                    this.elements.createRoomForm.style.display = 'block';
                    this.elements.roomInfo.textContent = '房间未创建';
                } else {
                    this.elements.joinRoomForm.style.display = 'block';
                    this.elements.roomInfo.textContent = '房间已存在';

                    document.getElementById('currentPlayers').textContent = `${players_count}/${total_players - ai_players}`;
                    document.getElementById('aiCount').textContent = ai_players;
                    document.getElementById('roomStatus').textContent = this.getRoomStatusText(room_state);
                }
            }

            getRoomStatusText(state) {
                const statusMap = {
                    'waiting_for_players': '等待玩家',
                    'ready_to_start': '准备开始',
                    'game_in_progress': '游戏中',
                    'game_finished': '游戏结束'
                };
                return statusMap[state] || state;
            }

            updateAiOptions() {
                const totalPlayers = parseInt(this.elements.totalPlayers.value);
                const aiSelect = this.elements.aiPlayers;

                aiSelect.innerHTML = '';
                for (let i = 1; i < totalPlayers; i++) {
                    const option = document.createElement('option');
                    option.value = i;
                    option.textContent = `${i}个AI`;
                    if (i === Math.min(3, totalPlayers - 1)) {
                        option.selected = true;
                    }
                    aiSelect.appendChild(option);
                }
            }

            connectWebSocket() {
                const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
                const wsUrl = `${protocol}//${window.location.host}/ws`;

                this.ws = new WebSocket(wsUrl);

                this.ws.onopen = () => {
                    this.updateConnectionStatus(true);
                    this.log('WebSocket连接成功');
                };

                this.ws.onmessage = (event) => {
                    const message = JSON.parse(event.data);
                    this.handleMessage(message);
                };

                this.ws.onclose = () => {
                    this.updateConnectionStatus(false);
                    this.log('WebSocket连接断开');
                    setTimeout(() => this.connectWebSocket(), 3000);
                };

                this.ws.onerror = (error) => {
                    this.log('WebSocket错误: ' + error);
                };
            }

            updateConnectionStatus(connected) {
                this.elements.statusDot.className = 'status-dot' + (connected ? ' connected' : '');
                this.elements.connectionText.textContent = connected ? '已连接' : '连接断开';
            }

            handleMessage(message) {
                this.log(`收到消息: ${message.type}`);

                switch (message.type) {
                    case 'player_joined':
                        this.log(`${message.data.player_name} 加入房间`);
                        break;

                    case 'room_state':
                        this.handleRoomState(message.data);
                        break;

                    case 'game_started':
                        this.showGameInterface();
                        this.log('游戏开始！');
                        break;

                    case 'game_state':
                        this.updateGameState(message.data);
                        break;

                    case 'action_required':
                        this.handleActionRequired(message.data);
                        break;

                    case 'error':
                        this.log('错误: ' + message.data.message);
                        break;
                }
            }

            handleRoomState(data) {
                if (data.room_state === 'ready_to_start') {
                    this.elements.setupContainer.style.display = 'none';
                    this.elements.waitingRoom.style.display = 'block';
                    this.elements.startGameBtn.style.display = 'block';
                }
            }

            showGameInterface() {
                this.elements.setupContainer.style.display = 'none';
                this.elements.waitingRoom.style.display = 'none';
                this.elements.gameContainer.style.display = 'block';
            }

            updateGameState(data) {
                this.gameState = data;

                // 更新游戏信息
                this.elements.gameState.textContent = this.getGameStateText(data.game_state);
                this.elements.currentRound.textContent = data.round_name || '-';
                this.elements.potAmount.textContent = `$${data.pot}`;
                this.elements.currentBet.textContent = `$${data.current_bet}`;
                this.elements.toCall.textContent = `$${data.to_call}`;
                this.elements.minRaise.textContent = data.min_raise ? `$${data.min_raise}` : '-';

                // 更新公共牌
                this.updateCommunityCards(data.community_cards);

                // 更新手牌
                this.updateYourHand(data.your_hand);

                // 更新玩家列表
                this.updatePlayersList(data.players);

                // 更新操作面板
                this.updateActionPanel(data.your_turn, data.valid_actions);
            }

            getGameStateText(state) {
                const stateMap = {
                    'dealing_cards': '发牌中',
                    'posting_blinds': '下盲注',
                    'preflop_betting': '翻牌前下注',
                    'dealing_flop': '发翻牌',
                    'flop_betting': '翻牌圈下注',
                    'dealing_turn': '发转牌',
                    'turn_betting': '转牌圈下注',
                    'dealing_river': '发河牌',
                    'river_betting': '河牌圈下注',
                    'showdown': '摊牌',
                    'round_end': '回合结束'
                };
                return stateMap[state] || state;
            }

            updateCommunityCards(cards) {
                const container = this.elements.communityCards;
                container.innerHTML = '';

                for (let i = 0; i < 5; i++) {
                    const cardDiv = document.createElement('div');
                    cardDiv.className = 'card';

                    if (cards && cards[i]) {
                        const card = cards[i];
                        cardDiv.textContent = card.rank + card.suit;
                        if (card.suit === '♥' || card.suit === '♦') {
                            cardDiv.classList.add('red');
                        }
                    } else {
                        cardDiv.classList.add('empty');
                        cardDiv.textContent = '?';
                    }

                    container.appendChild(cardDiv);
                }
            }

            updateYourHand(hand) {
                const container = this.elements.yourHand;
                container.innerHTML = '';

                for (let i = 0; i < 2; i++) {
                    const cardDiv = document.createElement('div');
                    cardDiv.className = 'card';

                    if (hand && hand[i]) {
                        const card = hand[i];
                        cardDiv.textContent = card.rank + card.suit;
                        if (card.suit === '♥' || card.suit === '♦') {
                            cardDiv.classList.add('red');
                        }
                    } else {
                        cardDiv.classList.add('empty');
                        cardDiv.textContent = '?';
                    }

                    container.appendChild(cardDiv);
                }
            }

            updatePlayersList(players) {
                const container = this.elements.playersList;
                container.innerHTML = '';

                players.forEach(player => {
                    const li = document.createElement('li');
                    li.className = 'player-item';

                    if (player.folded) {
                        li.classList.add('folded');
                    }
                    if (player.is_current_player) {
                        li.classList.add('current-turn');
                    }

                    li.innerHTML = `
                        <div class="player-name">
                            ${player.name}
                            ${player.is_ai ? '<span class="ai-badge">AI</span>' : ''}
                        </div>
                        <div class="player-info">
                            <span>筹码: <span class="chips">$${player.chips}</span></span>
                            <span>下注: <span class="bet">$${player.current_bet}</span></span>
                            <span>状态: ${player.folded ? '已弃牌' : player.all_in ? '全押' : '正常'}</span>
                            <span>位置: ${player.is_current_player ? '当前' : '-'}</span>
                        </div>
                    `;

                    container.appendChild(li);
                });
            }

            updateActionPanel(yourTurn, validActions) {
                const waitingMsg = this.elements.waitingMessage;
                const yourTurnSection = this.elements.yourTurnSection;
                const actionSection = this.elements.actionSection;

                // 重置状态
                this.stopCountdown();
                this.hideBetInput();

                if (yourTurn && validActions && validActions.length > 0) {
                    // 轮到你行动
                    actionSection.classList.add('your-turn');
                    waitingMsg.style.display = 'none';
                    yourTurnSection.style.display = 'block';

                    this.createActionButtons(validActions);
                } else {
                    // 等待其他玩家
                    actionSection.classList.remove('your-turn');
                    waitingMsg.style.display = 'block';
                    yourTurnSection.style.display = 'none';
                }
            }

            createActionButtons(validActions) {
                const container = this.elements.actionButtons;
                container.innerHTML = '';

                validActions.forEach(action => {
                    const button = document.createElement('button');
                    button.className = 'action-btn btn';

                    switch (action) {
                        case 'fold':
                            button.textContent = '弃牌';
                            button.className += ' btn-danger';
                            button.onclick = () => this.sendAction('fold');
                            break;

                        case 'check':
                            button.textContent = '过牌';
                            button.onclick = () => this.sendAction('check');
                            break;

                        case 'call':
                            const callAmount = this.gameState ? this.gameState.to_call : 0;
                            button.textContent = `跟注 ${callAmount}`;
                            button.className += ' btn-success';
                            button.onclick = () => this.sendAction('call');
                            break;

                        case 'bet':
                            button.textContent = '下注';
                            button.onclick = () => this.showBetInput('bet');
                            break;

                        case 'raise':
                            button.textContent = '加注';
                            button.onclick = () => this.showBetInput('raise');
                            break;

                        case 'all_in':
                            button.textContent = '全押';
                            button.className += ' btn-danger';
                            button.onclick = () => this.sendAction('all_in');
                            break;
                    }

                    container.appendChild(button);
                });
            }

            handleActionRequired(data) {
                this.log(`轮到你行动: ${data.valid_actions.join(', ')}`);
                this.startCountdown(data.timeout);

                // 更新下注输入的范围
                if (data.min_raise) {
                    this.elements.betAmountInput.min = data.min_raise;
                    this.elements.betAmountInput.placeholder = `最小: ${data.min_raise}`;
                }
            }

            startCountdown(seconds) {
                this.countdownSeconds = seconds;
                this.updateCountdownDisplay();

                this.countdownTimer = setInterval(() => {
                    this.countdownSeconds--;
                    this.updateCountdownDisplay();

                    if (this.countdownSeconds <= 0) {
                        this.stopCountdown();
                        this.log('行动超时，自动弃牌');
                    }
                }, 1000);
            }

            updateCountdownDisplay() {
                this.elements.countdown.textContent = `剩余时间: ${this.countdownSeconds}秒`;

                // 时间不足时变红
                if (this.countdownSeconds <= 10) {
                    this.elements.countdown.style.color = '#ff4444';
                } else {
                    this.elements.countdown.style.color = '#ffd700';
                }
            }

            stopCountdown() {
                if (this.countdownTimer) {
                    clearInterval(this.countdownTimer);
                    this.countdownTimer = null;
                }
                this.elements.countdown.textContent = '';
            }

            showBetInput(action) {
                this.currentBetAction = action;
                this.elements.betInputSection.style.display = 'block';
                this.elements.betAmountInput.focus();

                // 设置默认值
                if (action === 'raise' && this.gameState && this.gameState.min_raise) {
                    this.elements.betAmountInput.value = this.gameState.min_raise;
                } else if (action === 'bet') {
                    this.elements.betAmountInput.value = this.gameState ? this.gameState.current_bet || 20 : 20;
                }
            }

            hideBetInput() {
                this.elements.betInputSection.style.display = 'none';
                this.currentBetAction = null;
            }

            confirmBet() {
                const amount = parseInt(this.elements.betAmountInput.value);

                if (!amount || amount <= 0) {
                    alert('请输入有效的下注金额');
                    return;
                }

                this.sendAction(this.currentBetAction, amount);
                this.hideBetInput();
            }

            cancelBet() {
                this.hideBetInput();
            }

            sendAction(action, amount = null) {
                if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
                    this.log('WebSocket未连接');
                    return;
                }

                const message = {
                    type: 'player_action',
                    data: { action }
                };

                if (amount !== null) {
                    message.data.amount = amount;
                }

                this.ws.send(JSON.stringify(message));
                this.log(`发送行动: ${action}${amount ? ` ${amount}` : ''}`);

                // 停止倒计时
                this.stopCountdown();
            }

            createRoom() {
                const playerName = this.elements.playerName.value.trim();
                const totalPlayers = parseInt(this.elements.totalPlayers.value);
                const aiPlayers = parseInt(this.elements.aiPlayers.value);

                if (!playerName) {
                    alert('请输入玩家昵称');
                    return;
                }

                this.playerName = playerName;
                this.sendMessage('join_room', {
                    player_name: playerName,
                    total_players: totalPlayers,
                    ai_players: aiPlayers
                });
            }

            joinRoom() {
                const playerName = this.elements.joinPlayerName.value.trim();

                if (!playerName) {
                    alert('请输入玩家昵称');
                    return;
                }

                this.playerName = playerName;
                this.sendMessage('join_room', {
                    player_name: playerName,
                    total_players: 4,  // 使用现有房间配置
                    ai_players: 3
                });
            }

            startGame() {
                this.sendMessage('start_game', {});
            }

            sendMessage(type, data) {
                if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
                    this.log('WebSocket未连接');
                    return;
                }

                const message = { type, data };
                this.ws.send(JSON.stringify(message));
                this.log(`发送消息: ${type}`);
            }

            log(message) {
                const logContainer = this.elements.messageLog;
                const logDiv = document.createElement('div');
                logDiv.className = 'log-message';

                const time = new Date().toLocaleTimeString();
                logDiv.innerHTML = `
                    <span class="log-time">${time}</span>
                    <div>${message}</div>
                `;

                logContainer.appendChild(logDiv);
                logContainer.scrollTop = logContainer.scrollHeight;

                // 限制日志数量
                while (logContainer.children.length > 50) {
                    logContainer.removeChild(logContainer.firstChild);
                }
            }
        }

        // 初始化游戏
        document.addEventListener('DOMContentLoaded', () => {
            new PokerGame();
        });
    </script>
</body>
</html>